package com.zzc.legou.auth.service.impl;

import com.zzc.legou.auth.client.UserClient;
import com.zzc.legou.security.api.po.Role;
import com.zzc.legou.security.api.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class AuthServiceImpl implements UserDetailsService {

    @Autowired
    private UserClient userClient;

    @Autowired
    private PasswordEncoder passwordEncoder;

    /**
     * 查询用户的姓名和密码 以及授权信息的放入
     * @param s
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        User user = userClient.getByUserName(s);
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        List<GrantedAuthority> getAuthorities = new ArrayList<>();
        if (null != user) {
            List<Role> roles = userClient.selectRolesByUserId(user.getId());
            for (Role role : roles) {
                GrantedAuthority authority = new SimpleGrantedAuthority("ROLE_" + role.getName());
                getAuthorities.add(authority);
            }
        }
        return new com.zzc.legou.auth.entity.User(user.getPassword(), user.getUserName(),getAuthorities);
    }
}
